import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

import { useLoginStore } from '@/stores/login'

export const useCartStore = defineStore('cart', () => {

  const cartList = ref([]) // 购物车列表
  // 调用addAction方法添加商品
  const addAction = (cartList1) => {  // 添加商品id和数量
    console.log(cartList1)
    if (cartList.value.length === 0) { // 判断购物车列表中是否有商品
      cartList.value.push(cartList1) // 如果没有该商品则添加商品
    } else {
      // 如果有该商品则修改商品数量
      if (cartList.value.some(item => item.skuId === cartList1.skuId)) {
        cartList.value.forEach(item => {
        if (item.skuId === cartList1.skuId) {
          item.numcount += cartList1.numcount
        }
      })
      }else {
        cartList.value.push(cartList1)
      }

    }
  }
  // 商品的总数量
  const total = computed(() => {
    return cartList.value.reduce((pre, item) => {
      return pre + item.numcount
    }, 0)
  })


  const total2 = computed(() => {
    const itemlist =  cartList.value.filter(item => item.selected === true)
    return itemlist.length
  })



  // 提交商品订单成功后 清空购物车数据
  const gouwuchelist = () => {
    cartList.value = []
  }


  // 计算选择的商品的总价
  const price = computed(() => cartList.value.filter(item => item.selected).reduce((a ,b) => a + b.price * b.numcount, 0))
  // 删除指定的商品
  const delCart = (skuId) => {  // 头部购物车 删除指定的商品
    cartList.value =  cartList.value.filter(item => item.skuId !== skuId)
  }

  // 全选反选
  const suanze = ref(true)
  const choose = () => {
    cartList.value.forEach(item => {
      item.selected = !suanze.value
    })
  }



  // 小商品的选择
  const suanze1 = ((i,selected) => {
    const item = cartList.value.find(item => item.skuId === i.skuId)
    item.selected = selected

    const isAll = cartList.value.every(item => item.selected)
    suanze.value = isAll

  })



  const LoingCart = computed(() => {
    const uselongin = useLoginStore()
    if (uselongin.UserList.token === undefined) {
      return false
    } else {
      return true
    }
  })


  return { gouwuchelist, cartList, addAction,  total, price, delCart, suanze, choose, suanze1,total2, LoingCart}
},
  { persist: true }
)
